package com.hbun.cxcy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbun.cxcy.common.utils.PageUtils;
import com.hbun.cxcy.common.utils.R;
import com.hbun.cxcy.entity.Apply;
import com.hbun.cxcy.service.ApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mahaunyu
 * @since 2022-01-24
 */
@CrossOrigin
@RestController
@RequestMapping("/cxcy/apply")
public class ApplyController {
    @Autowired
    private ApplyService applyService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("cxcyweb:apply:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = applyService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("cxcyweb:apply:info")
    public R info(@PathVariable("id") Long id) {
        Apply apply = applyService.getById(id);

        return R.ok().put("apply", apply);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("cxcyweb:apply:save")
    public R save(@RequestBody Apply apply) {
//		applyService.save(apply);
        System.out.println(apply);
        // 当学号在数据库中存在时，说明已经保存过，不保存历史记录，以最后一次提交为主，所以用更新操作
        String stuNumber = apply.getStuNumber();
        QueryWrapper<Apply> wrapper = new QueryWrapper<Apply>().eq("stu_number", stuNumber);
        List<Apply> list = applyService.list(wrapper);
        if (list.size() == 1) {
            Long id = list.get(0).getId();
            apply.setId(id);
            applyService.updateByIdWithTime(apply);
        } else if (list.isEmpty()) {
            applyService.saveWithCustom(apply);
        }
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("cxcyweb:apply:update")
    public R update(@RequestBody Apply apply) {
        //TODO 将更新时间写入
        applyService.updateByIdWithTime(apply);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("cxcyweb:apply:delete")
    public R delete(@RequestBody Long[] ids) {

        applyService.removeByIdsWithCustom(Arrays.asList(ids));

        return R.ok();
    }
}

